package com.gitee.wsl.flowing.pipeline.context

import com.gitee.wsl.flowing.pipeline.PipelineInterceptorFunction
import kotlinx.coroutines.CoroutineScope
import kotlin.coroutines.CoroutineContext

internal  val DISABLE_SFG: Boolean = false

/**
 * Represents running execution of a pipeline
 *
 * @param context: object representing context in which pipeline executes
 */

 abstract class PipelineContext<TSubject : Any, TContext : Any>(
     val context: TContext
) : CoroutineScope {

    /**
     * Subject of this pipeline execution that goes along the pipeline
     */
     abstract var subject: TSubject

    /**
     * Finishes current pipeline execution
     */
     abstract fun finish()

    /**
     * Continues execution of the pipeline with the given subject
     */
     abstract suspend fun proceedWith(subject: TSubject): TSubject

    /**
     * Continues execution of the pipeline with the same subject
     */
     abstract suspend fun proceed(): TSubject

    internal abstract suspend fun execute(initial: TSubject): TSubject
}

/**
 * Build a pipeline of the specified [interceptors] and create executor.
 */
internal fun <TSubject : Any, TContext : Any> pipelineContextFor(
    context: TContext,
    interceptors: List<PipelineInterceptorFunction<TSubject, TContext>>,
    subject: TSubject,
    coroutineContext: CoroutineContext,
    debugMode: Boolean = false
): PipelineContext<TSubject, TContext> = if (DISABLE_SFG || debugMode) {
    DebugPipelineContext(context, interceptors, subject, coroutineContext)
} else {
    SuspendFunctionGun(subject, context, interceptors)
}

